package com.xxx.dict.controller;

import com.github.pagehelper.PageInfo;
import com.xxx.base.utils.R;
import com.xxx.dict.domain.Dict;
import com.xxx.dict.query.DictQuery;
import com.xxx.dict.service.IDictService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequiredArgsConstructor
@RequestMapping("/dict")
@Api(tags = "数据字典类")
public class DictController {

    private final IDictService dictService;

    @GetMapping
    @ApiOperation(value = "查询所有")
    public R<List<Dict>> findAll() {
        List<Dict> dicts = dictService.findAll();
        return R.ok(dicts);
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查询")
    public R<Dict> findById(@PathVariable Long id) {
        Dict one = dictService.findOne(id);
        return R.ok(one);
    }

    @PutMapping
    @ApiOperation(value = "根据id更新或增加")
    public R<Void> addOrUpdateDict(@RequestBody Dict dict) {
        try {
            if (dict.getId() == null || dict.getId() == 0) {
                dictService.addDict(dict);
            } else {
                dictService.updateDict(dict);
            }
        } catch (Exception e) {
            return R.fail("用户名已经存在");
        }
        return R.ok();
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除一个")
    public R<Object> deleteDict(@PathVariable Long id) {
        dictService.deleteDict(id);
        return R.ok();
    }

    @PatchMapping
    @ApiOperation(value = "批量删除")
    public R<Object> batchDeleteDict(@RequestBody Long[] ids) {
        try {
            dictService.batchDict(ids);
        } catch (Exception e) {
            return R.fail("删除失败");
        }
        return R.ok();
    }

    @PostMapping
    @ApiOperation(value = "批量查询")
    public PageInfo<Dict> queryPage(@RequestBody DictQuery dictQuery) {
        List<Dict> dictQueries = dictService.queryPage(dictQuery);
        return new PageInfo<>(dictQueries);
    }
}
